package com.appspot.didit.client.tag;

import java.util.HashMap;

import com.appspot.didit.client.BaseView;
import com.appspot.didit.client.user.UserManager;
import com.appspot.didit.client.user.UserService;
import com.appspot.didit.client.user.UserServiceAsync;
import com.appspot.didit.client.util.Util;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class TagManagePresenterImpl implements TagManagePresenter {
	private final UserServiceAsync userService = GWT.create(UserService.class);
	private final TagServiceAsync tagService = GWT.create(TagService.class);

	private final View view;

	@Inject
	public TagManagePresenterImpl(final HandlerManager eventBus, final View view) {
		this.view = view;
		view.getCombineClickHandlers().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				String tags = view.getTags().getValue();
				String combinedTag = view.getCombinedTag().getValue();
				if (combinedTag.contains(" ")) {
					MessageBox.alert("Alert",
							"leerzeichen ist in Name eines Tages verboten",
							null);
					return;
				}
				HashMap<String, Tag> tagIndex = TagManager.getInstance()
						.getMyTagNameIndex();
				if (!tags.contains(" ")) {
					if (!tagIndex.containsKey(combinedTag)) {
						Tag tag = tagIndex.get(tags);
						tag.setTagname(combinedTag);
						tagService.update(tag, new AsyncCallback() {
							public void onFailure(Throwable caught) {
								GWT.log("Failed to update a Tag", caught);
							}

							public void onSuccess(Object result) {
								view.getTags().setValue("");
								view.getCombinedTag().setValue("");
								GWT.log("sucessfully updated a Tag", null);
							}
						});
					} else {
						Tag tagA = tagIndex.get(combinedTag);
						Tag tagB = tagIndex.get(tags);
						if (tagA.getId() != tagB.getId()) {
							tagService.combineAAndBAsA(tagA, tagB,
									new AsyncCallback() {
										public void onFailure(Throwable caught) {
											GWT.log("Failed to update a Tag",
													caught);
										}

										public void onSuccess(Object result) {
											view.getTags().setValue("");
											view.getCombinedTag().setValue("");
											GWT
													.log(
															"sucessfully updated a Tag",
															null);
										}
									});
						}
					}
				} else if (tagIndex.containsKey(combinedTag)) {
					Tag tagA = tagIndex.get(combinedTag);
					for (String t : Util.splitStringInArray(tags)) {
						Tag tagB = tagIndex.get(t);
						if (tagA.getId() != tagB.getId()) {
							tagService.combineAAndBAsA(tagA, tagB,
									new AsyncCallback() {
										public void onFailure(Throwable caught) {
											GWT.log("Failed to update a Tag",
													caught);
										}

										public void onSuccess(Object result) {
											GWT
													.log(
															"sucessfully updated a Tag",
															null);
										}
									});
						}
					}
					view.getTags().setValue("");
					view.getCombinedTag().setValue("");
				} else {
					String[] t = Util.splitStringInArray(tags);
					Tag tagA = tagIndex.get(t[0]);
					tagA.setTagname(combinedTag);
					tagService.update(tagA, new AsyncCallback() {
						public void onFailure(Throwable caught) {
							GWT.log("Failed to update a Tag", caught);
						}

						public void onSuccess(Object result) {
							view.getTags().setValue("");
							view.getCombinedTag().setValue("");
							GWT.log("sucessfully updated a Tag", null);
						}
					});
					for (int i = 1; i < t.length; i++) {
						Tag tagB = tagIndex.get(t[i]);
						if (tagA.getId() != tagB.getId()) {
							tagService.combineAAndBAsA(tagA, tagB,
									new AsyncCallback() {
										public void onFailure(Throwable caught) {
											GWT.log("Failed to update a Tag",
													caught);
										}

										public void onSuccess(Object result) {
											GWT
													.log(
															"sucessfully updated a Tag",
															null);
										}
									});
						}
					}
					view.getTags().setValue("");
					view.getCombinedTag().setValue("");
				}
			}

		});
		
		view.getInviteClickHandlers().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String tagString = view.getTag().getValue();
				String users = view.getInvite().getValue();
				final Tag t = TagManager.getInstance().getMyTagNameIndex().get(tagString);
				for(String user : Util.splitStringInArray(users)) {
					final String u = user;
					if(u.contains("@")) {
						tagService.sendInvitation(t, u, new AsyncCallback() {
							public void onFailure(Throwable caught) {
								GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
							}	
						    public void onSuccess(Object result) {
						        GWT.log("Einladung ausgeschickt!", null);
						    }
	                    });
					}
				}
				MessageBox.alert("Alert", "Einladung ausgeschickt!", null);
				view.getInvite().setValue("");
				
			}
        });
		bindEvents(eventBus);
	}

	private void bindEvents(final HandlerManager eventBus) {

	}

	public BaseView getView() {
		return view;
	}

	public View showTagManage() {
		return view;
	}
}
